import java.util.Arrays;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
//选择排序,比之冒泡排序,它的优点在于减少了交换次数
public class SelectSort {
    public static void main(String[] args) {
        //selectSort(new int[] {1,2,5,8,-4,3,5,7,-11,-5,20,98});

        int[] arr = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i] = (int) (Math.random() * 80000);
        }

        long start = System.currentTimeMillis();
        selectSort(arr);

        long end = System.currentTimeMillis();
        System.out.println(end - start);  //4615  ,选择排序80000个随机数据的数组需要的ms数
    }


    public static int[] selectSort(int arr[]) {
        // 将变量定义在循环外面可以减少一定的开销
        int min = 0;
        int minIndex = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            min = arr[i];
            minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (min > arr[j]) {
                    min = arr[j];
                    minIndex = j;
                }
            }
            //当minIndex=i时,说明这个值就是要找的最小值,则不进行交换
            if (minIndex != i) {
                arr[minIndex] = arr[i];
                arr[i] = min;
            }
        }

        return arr;
    }
}
